package com.wt.struggle.goodbye.main.fragment

import android.Manifest
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Geocoder
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v7.widget.StaggeredGridLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.gson.reflect.TypeToken
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.*
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.NewsInfo
import com.wt.struggle.goodbye.main.activity.InvitationDetailsActivity
import com.wt.struggle.goodbye.main.adapter.TuiShopAdapter
import kotlinx.android.synthetic.main.main_fragment_3.*

class MainFragment3 : ProV4Fragment() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {

        when (what) {
            Send.SEARCH_LIST -> {

                if (refreshView != null) {
                    refreshView.isRefreshing = false
                }

                removeLoadDialog()

                if (netInfo.code == Config.SUCCESS) {

                    val result = netInfo.dataResult
                    if (result != null && result != "" && result != "null") {
                        val arr = gson!!.fromJson<ArrayList<NewsInfo>>(
                            result,
                            object : TypeToken<ArrayList<NewsInfo>>() {}.type
                        )

                        showAdapter(arr)

                    }
                }
            }
        }
    }

    private fun showAdapter(arr: ArrayList<NewsInfo>?) {

        if (arr != null && arr.size != 0) {

            if (isLoad) {
                adapter!!.updateData(arr)

            } else {
                adapter!!.updateDataClear(arr)
            }
            page++

        } else {
            showShortToast(activity!!, "无更多数据")
        }

    }

    override fun createView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.main_fragment_3, container, false)
    }

    var page = 1
    var isLoad = false

    var scanW = 0
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        scanW = ((getW(activity!!) - activity!!.resources.getDimension(R.dimen.dp_30))).toInt()

        initAdapter()

        page = 1
        isLoad = false

        refreshView.setOnRefreshListener {

            isLoad = false
            page = 1

            list.clear()

            if (adapter != null) {
                adapter!!.notifyDataSetChanged()
                adapter!!.cache!!.evictAll()
            }

            if (location != null) {

                get(location)

            } else {
                showShortToast(activity!!, "正在定位，请稍后重试！！")
            }

        }

        refreshView.onLoadMore(indexRecyclerView) {
            isLoad = true

            get(location)

        }

        if (isLocationEnabled(activity!!)) {
            initLocation()
        } else {
            showLocation()
        }

    }


    override fun onResume() {
        super.onResume()

    }


    var isVisibleCode = false

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        this.isVisibleCode = isVisibleToUser
    }


    private fun showLocation() {
        val dialog = AlertDialog.Builder(activity)
        dialog.setMessage("是否去设置打开位置服务?")
            .setPositiveButton("确定") { dd, i ->
                val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                startActivityForResult(intent, 6666)
                dd.dismiss()
            }.setNegativeButton("取消") { _, _ ->

            }.show()
    }


    fun get(location: Location?) {

        log("---------$location")

        send!!.getSearchList(page, 50, 0, 0, 0, "", location, handler!!)
        showLoadDialog(activity!!, "获取中")


    }


    val list = arrayListOf<NewsInfo>()

    var adapter: TuiShopAdapter? = null

    private fun initAdapter() {

        indexRecyclerView.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)

        indexRecyclerView.setHasTransientState(true)

        adapter = TuiShopAdapter(activity!!, list)

        adapter!!.setHasStableIds(true)

        adapter!!.code = 2
        adapter!!.location = location

        indexRecyclerView.adapter = adapter

        adapter!!.itemClickListener = object : ItemClickListener {

            override fun onItemClick(position: Int) {

                val intent = Intent(activity!!, InvitationDetailsActivity::class.java)
                intent.putExtra("info", list[position])
                startActivity(intent)

            }

            override fun onLongClick(position: Int) {

            }

        }

    }

    var locationManager: LocationManager? = null

    private fun initLocation() {
        val code = ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.ACCESS_FINE_LOCATION)
        val code2 = ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.ACCESS_COARSE_LOCATION)

        if (code == PackageManager.PERMISSION_GRANTED && code2 == PackageManager.PERMISSION_GRANTED) {

            locationManager = activity!!.getSystemService(Context.LOCATION_SERVICE) as LocationManager
            val locationProvider = LocationManager.NETWORK_PROVIDER
            // 获取Location
            location = locationManager!!.getLastKnownLocation(locationProvider)

            // 监视地理位置变化
            locationManager!!.requestLocationUpdates(locationProvider, 5000, 1f, locationListener)


        } else {

            ActivityCompat.requestPermissions(
                activity!!,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION),
                5678
            )
        }
    }


    var locationListener: LocationListener? = object : LocationListener {

        override fun onLocationChanged(p0: Location?) {
            this@MainFragment3.location = p0

            val geocoder = Geocoder(activity!!)

            val arr = geocoder.getFromLocation(location!!.latitude, location!!.longitude, 1);

            if (arr.size != 0) {
                val address = arr[0]
                addressStr = address.featureName
            }

            Share.saveLatLng(activity!!, location)

            get(location)


        }

        override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {

        }

        override fun onProviderEnabled(p0: String?) {

        }

        override fun onProviderDisabled(p0: String?) {

        }

    }


    var location: Location? = null
    var addressStr: String = ""

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 6666) {
            initLocation()
        }
    }

    override fun onStop() {
        super.onStop()

        if (locationManager != null) {

            locationManager!!.removeUpdates(locationListener)
            locationManager = null
            locationListener = null

        }

    }

}